import {
    Card,
    Breadcrumb,
    Form,
    Button,
    Radio,
    Input,
    Upload,
    Space,
    Select,
    message
    } from 'antd'
  import { PlusOutlined } from '@ant-design/icons'
  import { Link } from 'react-router-dom'
  import { useSearchParams } from 'react-router-dom'
  import './index.scss'
//   引入富文本编辑器相关的包
import ReactQuil from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { getChannelAPI,createArticleAPI,getArticleDetailAPI,updateArticleAPI } from '../../apis/arrticle'
import { useEffect,useState } from 'react'
import { useChannel } from '../../hooks/useChannel'
  const { Option } = Select
  const Publish = () => {
    // 定义文章列表的数据状态和修的方法
 const {article}=useChannel()
  // 回填数据
  const [searchParams]=useSearchParams()
  const articleId=searchParams.get('id')
    // 点击提交的事件
    const onFinish=async (formValue)=>{
        const {title,content,channel_id}=formValue
        // 1.按照文档格式处理表单数据
        const reqData={
            title,
            content,
            cover:{
                type:imageType,
                images:imageList.map(item=>{
                  if (item.response) {
                    return item.response.data.url
                  } else {
                    return item.url
                  }
                })
            },
            channel_id
        }
        // 2.发送请求
        // const res= await createArticleAPI(reqData)
        // console.log(res);
      //  根据id判断是调用新增接口还是更新接口
      if(articleId){
        // 更新接口
        updateArticleAPI({...reqData,id:articleId})
        message.success('更新成功')
        
      }else{
        createArticleAPI(reqData)
      }
    }
    const [imageList,setImageList]=useState([])
    // 上传图片的回调
     const onChange=(value)=>[
          // console.log('正在上传·')
          setImageList(value.fileList)
     ]
    //  切换选择图片类型
    const [imageType,setImageType]=useState([])
    const onTypeChange=(value)=>{
      console.log(value.target.value);
      setImageType(value.target.value)
    }
    const send=()=>{
      message.success('发布成功')

    }
   
    // 获取实例
    const [form] = Form.useForm();
    // console.log(articleId,"id是aaaaaaaaaaaa");
    useEffect(()=>{
    
     async function getArticle(){
      const res=await getArticleDetailAPI(articleId)
      console.log(res,"aaaaaa");
      form.setFieldsValue({
        ...res.data,
        type:res.data.cover.type
      })
      // 显示几张图片的模式
      setImageType(res.data.cover.type)
      // 显示图片
      setImageList(res.data.cover.images.map(url=>{
        return {url}
      }))
     }
    //  getArticle()
    if(articleId){
     getArticle()

    }
    },[articleId,form])
    return (
      <div className="publish">
        <Card
          title={
            <Breadcrumb items={[
              { title: <Link to={'/'}>首页</Link> },
              { title:  `${articleId?'编辑文章':'发布文章'}` },
            ]}
            />
          }
        >
          <Form
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            // 用来控制表单域里面的默认值
            initialValues={{ type: 0 }}
            onFinish={onFinish}
            form={form}
          > 
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '请输入文章标题' }]}
            >
              <Input placeholder="请输入文章标题" style={{ width: 400 }} />
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '请选择文章频道' }]}
            >
              <Select placeholder="请选择文章频道" style={{ width: 400 }}>
                {/* <Option value={0}>推荐</Option> */}
                {article.map(item=>{
                    // value属性是当用户选中时候会收集起来的字段，用于确定当前项，提交给后端
                    return <Option key={item.id} value={item.id}>{item.name}</Option>
                })}
              </Select>
            </Form.Item>
            <Form.Item label="封面">
  <Form.Item name="type">
    <Radio.Group onChange={onTypeChange}>
      <Radio value={1}>单图</Radio>
      <Radio value={3}>三图</Radio>
      <Radio value={0}>无图</Radio>
    </Radio.Group>
  </Form.Item>
 {
  imageType>0 &&  <Upload
  listType="picture-card"
  showUploadList
  action={'http://geek.itheima.net/v1_0/upload'}
  onChange={onChange}
  maxCount={imageType}
  name='image'
  fileList={imageList}
>
  <div style={{ marginTop: 8 }}>
    <PlusOutlined />
  </div>
</Upload>
 }
</Form.Item>
            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '请输入文章内容' }]}
            
            >
                {/* 富文本编辑器 */}
                <ReactQuil
                className='publish-quill'
                theme='snow'
                placeholder='请输入文章内容'
                ></ReactQuil>
            </Form.Item>
  
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit" onClick={send}>
                  发布文章
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
  
  export default Publish